package top.codecrab.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 可重入锁（递归锁）
 * synchronized是一个天然的可重入锁
 * <p>
 * ReentrantLock也是一个可重入锁：
 * 按照测试，不管有几个加锁都可以正常运行，不过有几个加锁就要有几个解锁，否则就会死锁。肯定一个锁好
 *
 * @author codecrab
 * @since 2021年06月30日 11:25
 */
public class ReentrantLockDemo {

    public static void main(String[] args) {
        Phone phone = new Phone();
        new Thread(phone, "t1").start();
        new Thread(phone, "t2").start();
    }

    private static void testSync() {
        Phone phone = new Phone();

        new Thread(phone::sendSms, "t1").start();
        new Thread(phone::sendSms, "t2").start();
    }
}

class Phone implements Runnable {
    public synchronized void sendSms() {
        System.out.println(Thread.currentThread().getName() + "\t发送一条短信");
        sendEmail();
    }

    public synchronized void sendEmail() {
        System.out.println(Thread.currentThread().getName() + "\t发送一条邮件");
    }

    Lock lock = new ReentrantLock();

    @Override
    public void run() {
        get();
    }

    public void get() {
        //按照测试，不管有几个加锁都可以正常运行，不过有几个加锁就要有几个解锁，否则就会死锁。肯定一个锁好
        lock.lock();
        //lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t执行了get()");
            set();
        } finally {
            lock.unlock();
            // lock.unlock();
        }
    }

    private void set() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t执行了set()");
        } finally {
            lock.unlock();
        }
    }
}
